/*
 * Sapphire backend
 *
 * Copyright (C) 2018 Alyssa Rosenzweig
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111-1301  USA
 *
 */

#include "push.h"
#include "websocket.h"

/* Has a push notification been sent since the last login? We default to TRUE
 * to avoid sporadic push notifications before the first connection*/

gboolean sapphire_already_pushed = TRUE;

/* We got a connection, so we're clear for another push */

void
sapphire_push_connected(void)
{
	sapphire_already_pushed = FALSE;
}

/* Send a push notification with the given content. This wrapper function
 * determines whether the notification should actually be pushed, handling
 * state appropriately. Actual medium-specific sending is delegated. */

extern gboolean sapphire_any_connected_clients;

void
sapphire_push_notification(Connection *conn, const gchar *content)
{
	/* Push notifications can only be sent if:
	 *
	 * 	0. Push notifications are enabled (TODO)
	 * 	1. There are no connected clients
	 * 	2. There has not been another push notification sent
	 *
	 * Check these criteria
	 */

	if (sapphire_any_connected_clients) return;
	if (sapphire_already_pushed) return;

	/* We've passed the criteria, so send the notification via the proxy */

	JsonObject *resp = json_object_new();
	json_object_set_string_member(resp, "op", "push");
	json_object_set_string_member(resp, "content", content);

	gchar *str = json_object_to_string(resp);
	gchar *str_prefixed = g_strdup_printf(">%s", str);
	sapphire_send_raw_packet(str_prefixed);
	json_object_unref(resp);
	g_free(str_prefixed);
	g_free(str);

	/* Record that we pushed something */
	sapphire_already_pushed = TRUE;
}
